package cn.accjiyun.controller.production;

import cn.accjiyun.common.controller.BaseController;
import cn.accjiyun.common.entity.PageModel;
import cn.accjiyun.common.entity.QueryEntity;
import cn.accjiyun.common.utils.WebUtils;
import cn.accjiyun.entity.production.ContractType;
import cn.accjiyun.entity.production.Land;
import cn.accjiyun.entity.production.LandType;
import cn.accjiyun.service.production.LandService;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jiyun on 2017/5/3.
 */
@Controller
@RequestMapping("/admin/production")
public class AdminLandController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(AdminLandController.class);
    private static String addLandPage = getViewPath("/admin/production/land-add");
    private static String landListPage = getViewPath("/admin/production/land-list");

    @Autowired
    private LandService landService;

    @InitBinder({"land"})
    public void initBinderSysUser(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("land.");
    }

    /**
     * 创建土地
     *
     * @return Map<String,Object>
     */
    @RequestMapping("/createLand")
    @ResponseBody
    public String createLand(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String landName = request.getParameter("landName");
            double area = Double.valueOf(request.getParameter("area").trim());
            String landTypeName = request.getParameter("landTypeName");
            double totalPrice = Double.valueOf(request.getParameter("totalPrice").trim());
            Integer contractId = Integer.valueOf(request.getParameter("contractId").trim());
            String contractTypeName = request.getParameter("contractTypeName");
            Timestamp insureStartDate = WebUtils.stringToTimestamp(request.getParameter("insureStartDate"));
            double deadline = Double.valueOf(request.getParameter("deadline").trim());
            double realTotalPrice = Double.valueOf(request.getParameter("realTotalPrice").trim());
            String transferor = request.getParameter("transferor");
            String assignee = request.getParameter("assignee");
            String mobile = request.getParameter("mobile");
            String comments = request.getParameter("comments");

            Land land = new Land();
            land.setLandName(landName);
            land.setArea(area);
            LandType landType = landService.queryLandTypeIdByName(landTypeName);
            land.setLandTypeByLandTypeId(landType);
            land.setTotalPrice(totalPrice);
            land.setContractId(contractId);
            ContractType contractType = landService.queryContractTypeIdByName(contractTypeName);
            land.setContractTypeByContractTypeId(contractType);
            land.setInsureStartDate(insureStartDate);
            land.setDeadline(deadline);
            land.setRealTotalPrice(realTotalPrice);
            land.setTransferor(transferor);
            land.setAssignee(assignee);
            land.setMobile(mobile);
            land.setComments(comments);

            landService.createLand(land);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "添加成功");
            resultJson.addProperty("url", "/admin/production/landList");
        } catch (Exception e) {
            logger.error("AdminLand.createLand()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "添加失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/deleteLand")
    @ResponseBody
    public String deleteLand(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String[] landIdsString = request.getParameter("landId").split(",");
            int[] landIds = new int[landIdsString.length];
            for (int i = 0; i < landIdsString.length; i++) {
                landIds[i] = Integer.valueOf(landIdsString[i]);
            }
            if (landIdsString != null && landIdsString.length > 0) {
                landService.deleteLand(landIds);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "删除成功");
            resultJson.addProperty("url", "reload");
        } catch (Exception e) {
            logger.error("AdminLandController.deleteLand()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "删除失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/getLandList")
    @ResponseBody
    public String getLandList(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            QueryEntity queryEntity = new QueryEntity();
            Map eqParams = new HashMap();
            Map likeStrings = new HashMap();
            String landTypeName = request.getParameter("landTypeName");
            if (WebUtils.isValidateRealString(landTypeName)) {
                eqParams.put("landTypeByLandTypeId.landTypeId",
                        landService.queryLandTypeIdByName(landTypeName).getLandTypeId());
            }
            String keyword = request.getParameter("keyword");
            if (WebUtils.isValidateRealString(keyword)) {
                likeStrings.put("landName", keyword);
                likeStrings.put("transferor", keyword);
                likeStrings.put("assignee", keyword);
            }
            queryEntity.setEqParams(eqParams);
            queryEntity.setLikeStrings(likeStrings);
            queryEntity.setBeginCreateTime(WebUtils.stringToData(request.getParameter("start_date")));
            queryEntity.setEndCreateTime(WebUtils.stringToData(request.getParameter("end_date")));
            queryEntity.setDateKeyword("insureStartDate");
            PageModel<Land> page = new PageModel();
            page.setPageSize(5);
            int pageNo = Integer.valueOf(request.getParameter("pageNo"));
            page.setPageNo(pageNo);
            List<Land> landList = landService.queryLandPage(queryEntity, page);
            JsonArray array = new JsonArray();
            for (Land land : landList) {
                JsonObject list = new JsonObject();
                list.addProperty("landId", land.getLandId());
                list.addProperty("landName", land.getLandName());
                list.addProperty("area", land.getArea());
                list.addProperty("landTypeName", land.getLandTypeByLandTypeId().getLandTypeName());
                list.addProperty("totalPrice", land.getTotalPrice());
                list.addProperty("contractId", land.getContractId());
                list.addProperty("contractTypeName", land.getContractTypeByContractTypeId().getContractTypeName());
                list.addProperty("insureStartDate", WebUtils.timestampToString(land.getInsureStartDate()));
                list.addProperty("deadline", land.getDeadline());
                list.addProperty("realTotalPrice", land.getRealTotalPrice());
                list.addProperty("transferor", land.getTransferor());
                list.addProperty("assignee", land.getAssignee());
                list.addProperty("mobile", land.getMobile());
                list.addProperty("comments", land.getComments());
                array.add(list);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("pages", page.getTotalPageSize());
            JsonObject list = new JsonObject();
            list.add("list", array);
            resultJson.add("data", list);
        } catch (Exception e) {
            logger.error("AdminLandController.getLandList()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "获取列表失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/updateLand")
    @ResponseBody
    public String updateLand(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            int landId = Integer.valueOf(request.getParameter("landId"));
            String landName = request.getParameter("landName");
            double area = Double.valueOf(request.getParameter("area").trim());
            String landTypeName = request.getParameter("landTypeName");
            double totalPrice = Double.valueOf(request.getParameter("totalPrice").trim());
            Integer contractId = Integer.valueOf(request.getParameter("contractId").trim());
            String contractTypeName = request.getParameter("contractTypeName");
            Timestamp insureStartDate = WebUtils.stringToTimestamp(request.getParameter("insureStartDate"));
            double deadline = Double.valueOf(request.getParameter("deadline").trim());
            double realTotalPrice = Double.valueOf(request.getParameter("realTotalPrice").trim());
            String transferor = request.getParameter("transferor");
            String assignee = request.getParameter("assignee");
            String mobile = request.getParameter("mobile");
            String comments = request.getParameter("comments");

            Land land = landService.queryLandById(landId);
            land.setLandName(landName);
            land.setArea(area);
            LandType landType = landService.queryLandTypeIdByName(landTypeName);
            land.setLandTypeByLandTypeId(landType);
            land.setTotalPrice(totalPrice);
            land.setContractId(contractId);
            ContractType contractType = landService.queryContractTypeIdByName(contractTypeName);
            land.setContractTypeByContractTypeId(contractType);
            land.setInsureStartDate(insureStartDate);
            land.setDeadline(deadline);
            land.setRealTotalPrice(realTotalPrice);
            land.setTransferor(transferor);
            land.setAssignee(assignee);
            land.setMobile(mobile);
            land.setComments(comments);

            landService.updateLand(land);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("url", "reload");
            resultJson.addProperty("msg", "更新成功");
        } catch (Exception e) {
            logger.error("AdminLand.update()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "更新失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/landAdd")
    public ModelAndView initUserAddPage() {
        ModelAndView model = new ModelAndView();
        model.addObject("landTypeNameList", landService.queryAllLandTypeName());
        model.addObject("contractTypeNameList", landService.queryAllContractTypeName());
        model.setViewName(addLandPage);
        return model;
    }

    @RequestMapping("/landList")
    public ModelAndView initUserListPage() {
        ModelAndView model = new ModelAndView();
        model.addObject("landTypeNameList", landService.queryAllLandTypeName());
        model.addObject("contractTypeNameList", landService.queryAllContractTypeName());
        model.setViewName(landListPage);
        return model;
    }

}
